package com.longcai.cm.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.longcai.cm.base.aop.Log;
import com.longcai.cm.base.bean.PageVo;
import com.longcai.cm.base.bean.Pageable;
import com.longcai.cm.bean.OptionsUtil;
import com.longcai.cm.bean.R;
import com.longcai.cm.common.utils.RequestUtil;
import com.longcai.cm.domain.FaMember;
import com.longcai.cm.domain.JaServiceInfo;
import com.longcai.cm.domain.JaShop;
import com.longcai.cm.domain.Vo.JaShopVo;
import com.longcai.cm.service.FaMemberService;
import com.longcai.cm.service.JaServiceInfoService;
import com.longcai.cm.service.JaShopService;
import com.longcai.cm.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author LBX
 * @date 2024-07-30
 */
@RestController
@RequestMapping("/JaShop")
public class JaShopController {

    private final JaShopService jaShopService;

    private final FaMemberService faMemberService;

    private final JaServiceInfoService serviceInfoService;

    private final RedisService redisService;

    public JaShopController(JaShopService jaShopService , FaMemberService faMemberService, JaServiceInfoService serviceInfoService, RedisService redisService) {
        this.jaShopService = jaShopService;
        this.faMemberService = faMemberService;
        this.serviceInfoService = serviceInfoService;
        this.redisService = redisService;
    }

    @RequestMapping("/getList")
    public R<PageVo<JaShop>> getList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        PageVo<JaShop> result = jaShopService.getPageBean(pageInfo, JaShop.class);
        return R.success(result);
    }

    @RequestMapping("/getInfo")
    public R<JaShop> getList(String id) {
        JaShop result = jaShopService.getById(id);
        final String[] split = result.getServiceInfo().split(",");
        final List<JaServiceInfo> list = serviceInfoService.lambdaQuery().in(JaServiceInfo::getName, Arrays.asList(split)).list();
        List<OptionsUtil> optionsUtilList = new ArrayList<>(list.size());
        for (JaServiceInfo vo : list) {
            OptionsUtil selectVo = new OptionsUtil(vo.getId(),vo.getName());
            optionsUtilList.add(selectVo);
        }
        result.setServiceInfo(JSON.toJSONString(optionsUtilList));
        // if (StringUtils.isNotBlank(result.getServiceInfoItem())){
        //     final String[] splititem = result.getServiceInfoItem().split(",");
        //     final List<JaServiceInfo> listItem = serviceInfoService.lambdaQuery().in(JaServiceInfo::getName, Arrays.asList(splititem)).list();
        //     List<OptionsUtil> optionsUtilListItem = new ArrayList<>(listItem.size());
        //     for (JaServiceInfo vo : list) {
        //         OptionsUtil selectVo = new OptionsUtil(vo.getId(),vo.getName());
        //         optionsUtilListItem.add(selectVo);
        //     }
        //     result.setServiceInfoItem(JSON.toJSONString(optionsUtilListItem));
        // }
        return R.success(result);
    }

    /**
     * @param vo 插入实体
     * @return R
     */
    @Log
    @RequestMapping("/save")
    public R<String> save(JaShopVo vo) {
        boolean success;
        JaShop shop = new JaShop();
        BeanUtils.copyProperties(vo,shop);
        if (StringUtils.isNotBlank(vo.getId())) {
            success = jaShopService.updateById(shop);
        } else {
            vo.setCreateTime(DateUtil.now());
            success = jaShopService.save(shop);
        }
        if (StringUtils.isNotBlank(vo.getLat()) && StringUtils.isNotBlank(vo.getLng())) {
            jaShopService.insertPoint(vo.getLng(), vo.getLat(), vo.getId());
        }
        return success ? R.success() : R.error();
    }

    /**
     * @param vo      修改实体
     * @param request id
     * @return R
     */
    @Log
    @RequestMapping("/edit")
    public R<String> edit(JaShop vo, HttpServletRequest request) {
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            boolean success = jaShopService.updateById(vo);
            return success ? R.success() : R.error();
        } else {
            return R.error("id不能为空");
        }
    }

    /**
     * @param id 主键
     * @return R
     */
    @Log
    @RequestMapping("/delete/{id}")
    public R<String> deleteByPrimaryKey(@PathVariable("id") Integer id) {
        final boolean success = jaShopService.removeById(id);
        return success ? R.success() : R.error();
    }

    /**
     * 【API】----  删除多个数据
     *
     * @return R
     */
    @Log
    @RequestMapping("/delete")
    public R<String> delete(String ids) {
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            final boolean success = jaShopService.removeById(idString);
            if (!success) {
                return R.error();
            }
        }
        return R.success();
    }

    @Log
    @RequestMapping("/shopOwner")
    public R shopOwner(String shopId, String userId){
        List<FaMember> list = faMemberService.list(new LambdaQueryWrapper<FaMember>().eq(FaMember::getShopId, shopId).eq(FaMember::getShopRole,1));
        if (list.size()>0){
            return R.error("该门店已存在店长，请先接解除用户店长再设置");
        }
        FaMember faMember = faMemberService.getById(userId);
        if (faMember.getShopRole() == 1){
            return R.error("该用户已是门店店长，请选择其他用户");
        }

        FaMember member = faMemberService.getById(userId);
        member.setShopId(shopId);
        member.setShopRole(1);
        faMemberService.updateById(member);
        redisService.updateUser(JSON.toJSONString(member), member.getId() + "");
        return R.success();
    }


    @Log
    @RequestMapping("/unShopOwner")
    public R unShopOwner(String shopId, String userId){
        FaMember member = faMemberService.getById(userId);
        member.setShopId("");
        member.setShopRole(0);
        faMemberService.updateById(member);
        redisService.updateUser(JSON.toJSONString(member), member.getId() + "");
        return R.success();
    }
}
